import { reactive } from "vue";
import { storeKey } from "./injectKey.js";
import { forEachValue } from "./utils.js";
export default class VuexStore {
  constructor(options) {
    const store = this;
    store._state = reactive({ data: options.state || {} });
    const _getters = options.getters || {};
    const _mutations = options.mutations || {};
    const _actions = options.actions || {};
    store.getters = Object.create(null);
    store._mutations = Object.create(null);
    store._actions = Object.create(null);
    forEachValue(_getters, (fn, key) => {
      Object.defineProperty(store.getters, key, {
        get: () => fn(store.state),
      });
    });
    forEachValue(_mutations, (fn, key) => {
      store._mutations[key] = (payload) => fn.call(store, store.state, payload);
    });
    forEachValue(_actions, (fn, key) => {
      store._actions[key] = (payload) => fn.call(store, store, payload);
    });
  }
  commit = (type, payload) => {
    this._mutations[type](payload);
  };
  dispatch = (type, payload) => {
    this._actions[type](payload);
  };

  get state() {
    //类的属性，访问器属性
    return this._state.data;
  }
  install(app, injectKey) {
    // createApp(App).use(store, 'myStore')
    // provide 给app根组件一个，子组件向上查找
    // 把 store 实例提供给所有子组件，暴露的是store实例
    app.provide(injectKey || storeKey, this);
    //vue.property.$store vue2
    app.config.globalProperties.$store = this;
  }
}
